<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";
import { Application, Container, Graphics, Text } from "pixi.js";
import { gsap } from "gsap";

const gameContainer = ref(null);
const app = ref(null);
const centerItems = ref([]);
const rings = ref([]);
const textElements = ref([]);

const gameWidth = 800;
const gameHeight = 800;
const ringSize = 50; // 圆环子项的大小

onMounted(async () => {
  await initGame();
});

onBeforeUnmount(() => {
  // 清理文本元素
  textElements.value.forEach((element) => {
    element.remove();
  });

  // 清理PIXI应用
  if (app.value) {
    app.value.destroy(true);
  }
});

const initGame = async () => {
  // 创建PIXI应用
  app.value = new Application({
    width: gameWidth,
    height: gameHeight,
    backgroundColor: 0x1a1a1a,
    antialias: true,
    resolution: window.devicePixelRatio || 1,
    autoDensity: true,
    hello: true,
    preference: "webgl",
    powerPreference: "high-performance",
  });

  // 等待初始化完成
  await app.value.init();

  // 添加到DOM
  gameContainer.value.appendChild(app.value.canvas);

  // 创建游戏元素
  createStartPosition();
  createCenterDisplay();
  createRings();
};

const createStartPosition = () => {
  const startContainer = new Container();
  startContainer.position.set(gameWidth / 2, 100);

  // 创建固定展示项
  const item = new Graphics();
  item.beginFill(0x4a90e2);
  item.drawRoundedRect(-30, -30, 60, 60, 10);
  item.endFill();

  // 添加渐变边缘效果
  const gradient = new Graphics();
  gradient.beginFill(0x1a1a1a, 0);
  gradient.lineStyle(20, 0x1a1a1a, 1);
  gradient.drawRoundedRect(-40, -40, 80, 80, 15);
  gradient.endFill();

  startContainer.addChild(item);
  startContainer.addChild(gradient);
  app.value.stage.addChild(startContainer);
};

const createCenterDisplay = () => {
  const centerContainer = new Container();
  centerContainer.position.set(gameWidth / 2, gameHeight / 2);

  // 创建5个展示项
  for (let i = 0; i < 5; i++) {
    const item = new Container();

    const background = new Graphics();
    background.beginFill(0x4a90e2);
    background.drawRoundedRect(-30, -30, 60, 60, 10);
    background.endFill();

    item.addChild(background);
    item.position.y = i * 100;

    centerItems.value.push(item);
    centerContainer.addChild(item);
  }

  // 添加交互
  centerContainer.eventMode = "static";
  centerContainer.cursor = "pointer";
  centerContainer.on("pointerdown", spinCenterItems);

  app.value.stage.addChild(centerContainer);
};

const spinCenterItems = () => {
  // 随机选择一个位置
  const targetIndex = Math.floor(Math.random() * 5);
  const duration = 2;

  // 创建动画序列
  const tl = gsap.timeline();

  // 快速滚动动画
  tl.to(centerItems.value, {
    y: "+=500",
    duration: duration * 0.6,
    ease: "power1.in",
    stagger: {
      each: 0.1,
      from: "start",
    },
  })
    // 减速停止动画
    .to(centerItems.value, {
      y: `+=${100 * targetIndex}`,
      duration: duration * 0.4,
      ease: "power2.out",
      stagger: {
        each: 0.1,
        from: "start",
      },
    });
};

const createRings = () => {
  const ringConfigs = [
    { radius: 150, items: 4 },
    { radius: 200, items: 6 },
    { radius: 250, items: 8 },
  ];

  ringConfigs.forEach((config, index) => {
    createRing(config.radius, config.items, index);
  });
};

const createRing = (radius, itemCount, ringIndex) => {
  const container = new Container();
  container.position.set(gameWidth / 2, gameHeight / 2);

  // 创建子项
  for (let i = 0; i < itemCount; i++) {
    const angle = (i / itemCount) * Math.PI * 2;
    const item = createRingItem(angle, radius, ringIndex);
    container.addChild(item);
  }

  // 添加交互
  container.eventMode = "static";
  container.cursor = "pointer";
  container.on("pointerdown", () => spinRing(container, ringIndex));

  rings.value.push(container);
  app.value.stage.addChild(container);
};

const createRingItem = (angle, radius, ringIndex) => {
  const container = new Container();

  // 创建背景
  const background = new Graphics();
  background.beginFill(getRandomColor());
  background.drawRoundedRect(
    -ringSize / 2,
    -ringSize / 2,
    ringSize,
    ringSize,
    5
  );
  background.endFill();

  // 添加高光效果
  const highlight = new Graphics();
  highlight.beginFill(0xffffff, 0.2);
  highlight.drawRoundedRect(
    -ringSize / 2,
    -ringSize / 2,
    ringSize,
    ringSize / 5,
    5
  );
  highlight.endFill();

  container.addChild(background);
  container.addChild(highlight);

  // 创建HTML文本元素
  const textElement = document.createElement("div");
  textElement.textContent = `${ringIndex + 1}x`;
  textElement.style.cssText = `
    position: absolute;
    color: white;
    font-family: Arial;
    font-size: 16px;
    transform: translate(-50%, -50%);
    pointer-events: none;
    user-select: none;
  `;

  // 更新文本位置的函数
  const updateTextPosition = () => {
    const globalPosition = container.getGlobalPosition();
    textElement.style.left = `${globalPosition.x}px`;
    textElement.style.top = `${globalPosition.y}px`;
    textElement.style.transform = `translate(-50%, -50%) rotate(${container.rotation}rad)`;
  };

  // 添加到DOM和跟踪数组
  gameContainer.value.appendChild(textElement);
  textElements.value.push(textElement);

  // 在渲染循环中更新文本位置
  app.value.ticker.add(updateTextPosition);

  // 设置位置和旋转
  container.position.x = Math.cos(angle) * radius;
  container.position.y = Math.sin(angle) * radius;
  container.rotation = angle + Math.PI / 2;

  return container;
};

const spinRing = (ring, ringIndex) => {
  // 随机旋转角度 (2-5圈)
  const rotations = 2 + Math.random() * 3;
  const targetRotation = rotations * Math.PI * 2;

  gsap.to(ring, {
    rotation: targetRotation,
    duration: 2 + rotations * 0.5,
    ease: "power2.out",
    onComplete: () => {
      // 重置旋转角度到0-2π之间
      ring.rotation = ring.rotation % (Math.PI * 2);
      // 更新颜色
      updateRingColors(ring);
    },
  });
};

const updateRingColors = (ring) => {
  ring.children.forEach((item) => {
    const background = item.getChildAt(0);
    gsap.to(background, {
      tint: getRandomColor(),
      duration: 0.5,
      ease: "none",
    });
  });
};

const getRandomColor = () => {
  const colors = [0xff4444, 0x44ff44, 0x4444ff, 0xffff44, 0xff44ff, 0x44ffff];
  return colors[Math.floor(Math.random() * colors.length)];
};
</script>

<template>
  <div class="game-scene">
    <div ref="gameContainer" class="game-container"></div>
  </div>
</template>

<style scoped>
.game-scene {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #1a1a1a;
}

.game-container {
  width: 800px;
  height: 800px;
}
</style>
